module.exports = (router, app, R, { User }, { authMiddleware }) => {
  // 注册用户
  router.post('/users/register', async (req, res) => {
    const { username, password } = req.body
    if (!username || !password) {
      return res.json(R.errMsg('用户名或密码不能为空'))
    }
    const user = await User.findOne({ username })
    if (user) {
      return res.json(R.errMsg('用户名已存在'))
    }
    const newUser = new User({ username, password })
    await newUser.save()
    return res.json(R.msg('注册成功'))
  })

  // 登录
  router.post('/users/login', async (req, res) => {
    const { username, password } = req.body
    if (!username || !password) {
      return res.json(R.errMsg('用户名或密码不能为空'))
    }
    const user = await User.findOne({ username }).select('+password')
    if (!user) {
      return res.json(R.errMsg('该用户不存在'))
    }
    const isPasswordValid = require('bcrypt').compareSync(password, user.password)
    if (!isPasswordValid) {
      return res.json(R.errMsg('密码错误'))
    }
    const token = require('jsonwebtoken').sign({ id: user._id }, process.env.JWT_SECRET)
    return res.json(R.ok({ token }, '登录成功'))
  })

  // 查询所有用户
  router.get('/users', authMiddleware, async (req, res) => {
    const users = await User.find()
    return res.json(R.ok(users, '操作成功'))
  })

  app.use(router)
}
